import {
    mergeLocalCart,
    insertCart,
    getCartList,
    deleteCart,
    updateCart,
    checkAllCart,
    getNewCartGoods
} from '@/api/cart'
export default {
    namespaced: true,
    state() {
        return {
            // 购物车的字段: id skuId name picture price nowPrice count attrsText selected stock isEffective isCollect discount
            lists: [] // list是关键字
        }
    },
    getters: {
        // 有效的购物车数据
        validList: state => state.lists.filter(item => item.isEffective),
        // 无效的购物车数据
        inValidList: state => state.lists.filter(item => !item.isEffective),
        // 选中的有效商品
        validSelectedList: (state, getters) => getters.validList.filter(item => item.selected),
        // 获取有效的购物车商品件数
        validTotal: (state, getters) => getters.validList.reduce((prev, current) => prev + current.count, 0),

        // 获取邮箱的购物车商品总金额
        validAmount: (state, getters) => getters.validList.reduce((prev, current) => prev + current.nowPrice * current.count, 0.00).toFixed(2),
        // 选中的有效商品件数
        validSelectedTotal: (state, getters) => getters.validList.filter(item => item.selected).reduce((prev, current) => prev + current.count, 0),
        // 选中的有效商品总金额
        validSelectedAmount: (state, getters) => getters.validList.filter(item => item.selected).reduce((prev, current) => prev + current.nowPrice * current.count, 0.00).toFixed(2),
        // 全选/全不选
        isAll: (state, getters) => getters.validList.every(item => item.selected) && getters.validList.length !== 0
    },
    mutations: {
        // 设置购物车数据
        setCartList(state, lists) {
            state.lists = lists
        },
        // 添加购物车
        // good是包含 id skuId name picture price nowPrice count attrsText selected stock的对象
        insertCart(state, good) {
            // 同一件(skuId相同)商品，不要重复产生多条数据，应该进行数量的增加
            const row = state.lists.find(item => item.skuId === good.skuId)
            if (row) {
                row.count += good.count
            } else {
                state.lists.unshift(good)
            }
        },
        // 删除购物车数据
        delCart(state, skuId) {
            state.lists = state.lists.filter(item => item.skuId !== skuId)
        },
        // 全选/全不选
        checkAll(state, status) {
            state.lists.filter(item => item.isEffective).forEach(item => {
                item.selected = status
            })
        },
        // 更改购物车数据
        // good中必须包含skuId 这个选项
        // {skuId:1,selected:false}
        updateCart(state, goods) {
            // 查询出skuId对应的商品数据
            const list = state.lists.find(item => item.skuId === goods.skuId)
            for (const key in goods) {
                if (goods[key] !== null && goods[key] !== undefined && goods[key] !== '') {
                    list[key] = goods[key]
                }
            }
        },
        // 批量删除选中的商品
        batchDeleteCart(state) {
            state.lists = state.lists.filter(item => !item.selected)
        },
        // 清除无效商品
        batchDeleteInvalidCart(state) {
            state.lists = state.lists.filter(item => item.isEffective)
        }
    },
    actions: {
        // 添加购物车
        insertCart(context, good) {
            return new Promise((resolve, reject) => {
                if (context.rootState.user.profile.token) {
                    // 登录
                    // 添加购物车数据到数据库
                    insertCart({
                        skuId: good.skuId,
                        count: good.count
                    }).then(() => {
                        // 从数据库查询最新的购物车数据
                        return getCartList()
                    }).then(data => {
                        // 修改本地购物车数据
                        context.commit('setCartList', data.result)
                        resolve()
                    })
                } else {
                    // 未登录
                    context.commit('insertCart', good)
                    resolve()
                }
            })
        },
        // 删除购物车数据
        delCart(context, skuId) {
            return new Promise((resolve, reject) => {
                if (context.rootState.user.profile.token) {
                    // 登录
                    deleteCart([skuId]).then(() => {
                        return getCartList()
                    }).then(data => {
                        context.commit('setCartList', data.result)
                        resolve()
                    })
                } else {
                    // 未登录
                    context.commit('delCart', skuId)
                    resolve()
                }
            })
        },
        // 根据全选/全不选复选框更改购物车数据
        checkAllCart(context, status) {
            return new Promise((resolve, reject) => {
                if (context.rootState.user.profile.token) {
                    // 登录
                    const skuIds = context.getters.validList.map(item => item.skuId)
                    checkAllCart({
                        selected: status,
                        ids: skuIds
                    }).then(() => {
                        return getCartList()
                    }).then(data => {
                        context.commit('setCartList', data.result)
                        resolve()
                    })
                } else {
                    // 未登录
                    context.commit('checkAll', status)
                    resolve()
                }
            })
        },
        // 更改购物车商品的状态
        updateCart(context, good) {
            return new Promise((resolve, reject) => {
                if (context.rootState.user.profile.token) {
                    // 登录
                    const {
                        skuId,
                        selected,
                        count
                    } = good
                    updateCart({
                        skuId,
                        selected,
                        count
                    }).then(() => {
                        return getCartList()
                    }).then(data => {
                        context.commit('setCartList', data.result)
                        resolve()
                    })
                } else {
                    // 未登录
                    context.commit('updateCart', good)
                    resolve()
                }
            })
        },
        // 更改购物车的sku选项
        updateCartSku(context, data) {
            return new Promise((resolve, reject) => {
                if (context.rootState.user.profile.token) {
                    // 登录
                    // 没有直接提供登录后修改sku的接口，但是可以通过调先删除旧的，再添加新的接口共同完成修改sku的功能
                    const oldSkuId = data.oldSkuId
                    const oldGood = context.state.lists.find(item => item.skuId === oldSkuId)

                    // 修改后的sku数据
                    const newSku = data.sku

                    // 先删再加再存
                    deleteCart([oldSkuId]).then(() => {
                        return insertCart({
                            skuId: newSku.skuId,
                            count: oldGood.count
                        })
                    }).then(() => {
                        return getCartList()
                    }).then(data => {
                        context.commit('setCartList', data.result)
                        resolve()
                    })
                } else {
                    // 未登录
                    // 先根据旧的skuId找到该条数据的其他的选项，和最新的商品的sku数据组合
                    const oldGood = context.state.lists.find(item => item.skuId === data.oldSkuId)

                    // 组合数据
                    const newGood = {
                        ...oldGood,
                        ...data.sku
                    }

                    // 删除掉原数据
                    context.commit('delCart', data.oldSkuId)

                    // 重新添加
                    context.commit('insertCart', newGood)
                    resolve()
                }
            })
        },
        // 批量删除选中的商品
        batchDeleteCart(context) {
            return new Promise((resolve, reject) => {
                if (context.rootState.user.profile.token) {
                    // 登录
                    const skuIds = context.getters.validSelectedList.map(item => item.skuId)
                    deleteCart(skuIds).then(() => {
                        return getCartList()
                    }).then(data => {
                        context.commit('setCartList', data.result)
                        resolve()
                    })
                } else {
                    // 未登录
                    context.commit('batchDeleteCart')
                    resolve()
                }
            })
        },
        // 批量删除无效的商品
        batchDeleteInvalidCart(context) {
            return new Promise((resolve, reject) => {
                if (context.rootState.user.profile.token) {
                    // 登录
                    const skuIds = context.getters.inValidList.map(item => item.skuId)
                    deleteCart(skuIds).then(() => {
                        return getCartList()
                    }).then(data => {
                        context.commit('setCartList', data.result)
                        resolve()
                    })
                } else {
                    // 未登录
                    context.commit('batchDeleteInvalidCart')
                    resolve()
                }
            })
        },
        // 登录后合并购物车
        async mergeCart(context) {
            /* const cartList = []
                  context.state.lists.forEach(item => {
                     cartList.push({
                         skuId: item.skuId,
                         count: item.count,
                         selected: item.selected
                     })
                 }) */
            const cartList = context.state.lists.map(({
                skuId,
                count,
                selected
            }) => ({
                skuId,
                count,
                selected
            }))

            // 合并成功
            await mergeLocalCart(cartList)

            // 清空本地的购物车数据
            context.commit('setCartList', [])
        },
        // 每次查看购物车数据时都去重新获取购物车商品数据的最新信息：价格、是否有效、库存,在app-header-cart.vue中调用
        findNewCartGoods(context) {
            return new Promise((resolve, reject) => {
                if (context.rootState.user.profile.token) {
                    // 已经登录了
                    // 调获取最新购物车列表的api更新本地缓存数据
                    getCartList().then(data => {
                        context.commit('setCartList', data.result)
                        resolve()
                    })
                } else {
                    // 未登录
                    // 从本地购物车列表取出skuId,然后调查询接口，更新本地购物车数据
                    // 在循环中根据skuId调异步api,不能确保每条数据按照顺序得到，然后在里面又是根据skuId做同步更新，这样会导致查询到的数据的skuId和更新时skuId不一致

                    const skuIds = context.state.lists.map(item => item.skuId)
                    const promiseAll = context.state.lists.map(item => getNewCartGoods(item.skuId))

                    // Promise.all()执行，确保按照顺序执行
                    Promise.all(promiseAll).then(data => {
                        // console.log(data)
                        // console.log(skuIds)

                        // 同步更新
                        data.forEach((item, index) => {
                            context.commit('updateCart', {
                                skuId: skuIds[index],
                                ...item
                            })
                        })
                        resolve()
                    })
                }
            })
        }
    }
}